package xuegao.study.mall.rbac.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import xuegao.study.mall.common.constant.AuthConstant;
import xuegao.study.mall.common.domain.RoleResource;
import xuegao.study.mall.common.model.ums.UmsAdmin;
import xuegao.study.mall.common.model.ums.UmsAdminRoleRelation;
import xuegao.study.mall.common.model.ums.UmsResource;
import xuegao.study.mall.common.service.RedisService;
import xuegao.study.mall.rbac.service.UmsAdminCacheService;
import xuegao.study.mall.repo.dao.ums.UmsAdminDao;
import xuegao.study.mall.repo.dao.ums.UmsAdminRoleRelationDao;
import xuegao.study.mall.repo.dao.ums.UmsRoleDao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台用户缓存service实现类
 */
@Service
public class UmsAdminCacheServiceImpl implements UmsAdminCacheService {

    @Value("${redis.database}")
    private String REDIS_DATABASE;

    @Value("${redis.expire.common}")
    private Long REDIS_EXPIRE;

    @Value("${redis.key.admin}")
    private String REDIS_KEY_ADMIN;

    @Value("${redis.key.resourceList}")
    private String REDIS_KEY_RESOURCE_LIST;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UmsAdminDao umsAdminDao;

    @Autowired
    private UmsAdminRoleRelationDao umsAdminRoleRelationDao;

    @Autowired
    private UmsRoleDao umsRoleDao;

    @Override
    public UmsAdmin getAdmin(String username) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + username;
        Object value = redisService.get(key);
        if (value != null) {
            return (UmsAdmin)value;
        }
        return null;
    }

    @Override
    public void setAdmin(UmsAdmin admin) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + admin.getUsername();
        redisService.set(key, admin);
    }

    @Override
    public void delAdmin(Long adminId) {
        UmsAdmin admin = umsAdminDao.selectById(adminId);
        if (admin != null) {
            String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + admin.getUsername();
            redisService.del(key);
        }
    }

    @Override
    public List<UmsResource> getAdminResourceList(Long adminId) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":" + adminId;
        Object value = redisService.get(key);
        if (value != null) {
            return (List<UmsResource>)value;
        }
        return null;
    }

    @Override
    public void setAdminResourceList(Long adminId, List<UmsResource> resourceList) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":" + adminId;
        redisService.set(key, resourceList, REDIS_EXPIRE);
    }

    @Override
    public void delAdminResourceList(Long adminId) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":" + adminId;
        redisService.del(key);
    }

    @Override
    public void deleteResourceListByRoleId(Long roleId) {
        // 根据roleId删除的逻辑就是删除这个角色绑定下的所有用户资源缓存
        Map<String, Object> params = new HashMap<>();
        params.put("role_id", roleId);
        List<UmsAdminRoleRelation> relationList = umsAdminRoleRelationDao.selectByMap(params);
        if (relationList != null && relationList.size() > 0) {
            String keyPrefix = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":";
            List<String> keys = relationList.stream().map(relation -> keyPrefix + relation.getAdminId()).collect(Collectors.toList());
            redisService.del(keys);
        }
    }

    @Override
    public void deleteResourceListByRoleIds(List<Long> roleIds) {
        List<UmsAdminRoleRelation> relationList = umsAdminRoleRelationDao.selectByRoleIds(roleIds);
        if (relationList != null && relationList.size() > 0) {
            String keyPrefix = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":";
            List<String> keys = relationList.stream().map(relation -> keyPrefix + relation.getAdminId()).collect(Collectors.toList());
            redisService.del(keys);
        }
    }

    @Override
    public void delResourceListByResourceId(Long resourceId) {
        List<UmsAdminRoleRelation> relationList = umsAdminRoleRelationDao.getListByResourceId(resourceId);
        if (relationList != null && relationList.size() > 0) {
            String keyPrefix = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":";
            List<String> keys = relationList.stream().map(relation -> keyPrefix + relation.getAdminId()).collect(Collectors.toList());
            redisService.del(keys);
        }
    }

    @Override
    public void initResourceRoles() {
        List<RoleResource> allRoleResource = umsRoleDao.getAllRoleResource();
        Map<String, List<String>> resultMap = new HashMap<>();
        if (allRoleResource != null && allRoleResource.size() > 0) {
            for (RoleResource roleResource : allRoleResource) {
                List<UmsResource> resourceList = roleResource.getResourceList();
                if (resourceList != null && resourceList.size() > 0) {
                    for (UmsResource resource : resourceList) {
                        String url = resource.getUrl();
                        List<String> roleNames = resultMap.computeIfAbsent(url, k -> new ArrayList<>());
                        roleNames.add(roleResource.getId() + "_" + roleResource.getName());
                    }
                }
            }
        }
        String key = AuthConstant.RESOURCE_ROLES_MAP_KEY;
        redisService.hSetAll(key, resultMap);
    }
}
